package org.unisinos.gc.action;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.unisinos.gc.dao.AreaDAO;
import org.unisinos.gc.dao.CongressoDAO;
import org.unisinos.gc.form.CongressoForm;
import org.unisinos.gc.vo.Area;
import org.unisinos.gc.vo.Congresso;

public class GetCongressoDetailAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ActionErrors errors = new ActionErrors();
		ActionForward forward = null;
		try {
			super.execute(mapping, form, request, response);

			String codigo = (String) request.getParameter("codigo");

			CongressoForm congressoForm = (CongressoForm) form;
			congressoForm.setAreas(new ArrayList<Area>(AreaDAO.getAreaList()));
			
			if (StringUtils.isNotEmpty(codigo)) {
				Congresso congresso = CongressoDAO.getCongresso(Integer.parseInt(codigo));
				congressoForm.parseCongresso(congresso);
				congressoForm.setIdAreaList(CongressoDAO.loadCongressoArea(Integer.parseInt(codigo)));
				
				request.setAttribute("mode", "edit");
			}else {
				request.setAttribute("mode", "new");
			}
			forward = mapping.findForward("success");
		} catch (Exception e) {
			e.printStackTrace();
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("systemError"));
		}

		if (!errors.isEmpty()) {
			request.setAttribute("mode", "new");
			super.saveErrors(request, errors);
			forward = mapping.findForward("error");
		}

		return forward;
	}

}
